package com.dong.springbootadmindemo;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import de.codecentric.boot.admin.server.config.EnableAdminServer;
import de.codecentric.boot.admin.server.web.client.InstanceExchangeFilterFunction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.client.RestTemplate;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicInteger;

@SpringBootApplication
@EnableAdminServer
@Slf4j
public class SpringbootAdminDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootAdminDemoApplication.class, args);
    }

    @Autowired
    RestTemplate restTemplate;
    @Autowired
    JavaMailSender javaMailSender;
    @Autowired
    MailProperties mailProperties;
    @Autowired
    TemplateEngine templateEngine;

    @Value("${spring.boot.admin.notify.mail.to}")
    private String toEmail;

    private AtomicInteger atomicInteger = new AtomicInteger(1);
    @Bean
    public InstanceExchangeFilterFunction auditLog() {
        return (instance, request, next) -> next.exchange(request).doOnSubscribe((s) -> {
            if (request.url().getPath().contains("/health")){
                //获取监听的客户端ip
                String reqUrl = "http://" + request.url().getHost() +":"+  request.url().getPort() + "/actuator/metrics/jvm.memory.used";
                ResponseEntity<String> responseEntity = restTemplate.getForEntity(reqUrl, String.class);
                String body = responseEntity.getBody();
                //log.info("返回参数是:{}",body);
                JSONObject jsonObject = (JSONObject) JSONObject.parse(body);
                JSONArray measurements = jsonObject.getJSONArray("measurements");
                JSONObject measurement = measurements.getJSONObject(0);
                BigDecimal decimal = measurement.getBigDecimal("value");
                BigDecimal divide = decimal.divide(new BigDecimal(1024 * 1024));
                //内存小于200M 告警
                if (divide.compareTo(new BigDecimal(200)) == 1){
                    //创建要发送的信息 MimeMessage构建邮件，MimeMessageHelper构建邮件收发信息
                    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
                    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);

                    try {
                        if (atomicInteger.incrementAndGet()<3){
                            helper.setSubject("jvm内存爆了");
                            helper.setTo(toEmail);
                            helper.setFrom(mailProperties.getUsername());
                            Context context = new Context();
                            context.setVariable("name", "springbootAdmin_demo项目");
                            context.setVariable("content", "当前已用jvm内存大小是" + divide + "M");
                            String mail = templateEngine.process("mail", context);
                            helper.setText(mail, true);
                            javaMailSender.send(mimeMessage);
                            log.info("告警邮件发送成功");
                        }
                    } catch (MessagingException e) {
                        log.error("告警邮件发送失败！");
                    }
                }
            }
        });
    }
}
